import 'dart:convert';
import 'dart:ui';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yinshui_caiying/http/api_project.dart';
import 'package:yinshui_caiying/http/api_water.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/image_list_result_model.dart';
import 'package:yinshui_caiying/model/image_model.dart';
import 'package:yinshui_caiying/model/image_result_model.dart';
import 'package:yinshui_caiying/model/params_model.dart';
import 'package:yinshui_caiying/model/projectItem_model.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/model/user_real_data_reault.dart';
import 'package:yinshui_caiying/model/waterUser_list_model.dart';
import 'package:yinshui_caiying/model/water_type_model.dart';
import 'package:yinshui_caiying/pages/project/project_create.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/utils/inputformatter.dart';
import 'package:yinshui_caiying/widgets/action_text_button.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yinshui_caiying/widgets/base_scaffold.dart';
import 'package:yinshui_caiying/widgets/form/form_with_adPicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_number.dart';
import 'package:yinshui_caiying/widgets/form/form_with_radio.dart';
import 'package:yinshui_caiying/widgets/form/form_with_singlePicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textArea.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textField.dart';
import 'package:yinshui_caiying/widgets/loading.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:yinshui_caiying/widgets/modal_title.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';
import 'package:yinshui_caiying/widgets/noData.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';
import 'package:yinshui_caiying/widgets/picker/models/pickerItem_model.dart';
import 'package:yinshui_caiying/widgets/picker/pickers.dart';

class WaterUserListPage extends StatelessWidget {
  WaterUserListPageController vm = Get.put(WaterUserListPageController());
  CommonService commonService = Get.find();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    vm.context = context;
    return BaseScaffold(
      appBar: BackTitleBar(
        title: '用水户列表',
        hasback: true,
        action: Row(
          children: [
            ActionTextButton(
                title: '报警',
                width: 70.w,
                height: 34.h,
                onPressed: () {
                  Get.toNamed('/alarm');
                }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text(
          '采集',
          style: TextStyle(color: Colors.white, fontSize: 46.sp),
        ),
        onPressed: () {
          Get.toNamed('/collection',
              arguments: ParamsModel(
                  id: vm._pj_id, name: vm._pj_name, ad_id: vm._adId));
        },
        backgroundColor: MyColors.main,
      ),
      body: SafeArea(
        child: Column(
          children: [menuBar(), searchBar(), Obx(() => waterUserList())],
        ),
      ),
    );
  }

  ///按钮菜单栏
  Widget menuBar() {
    return Container(
      width: 1.sw,
      height: 140.h,
      decoration: BoxDecoration(color: Colors.white),
      child: Row(
        children: [
          // Expanded(
          //   child: TextButton(
          //       onPressed: () {
          //         Pickers.showAdPicker(
          //             selectData: vm._adId,
          //             data: vm.commonService.adList,
          //             onConfirm: (value) {
          //               vm._searchAdId(value);
          //             },
          //             onAll: (value) {
          //               vm._searchAdId(value);
          //             });
          //       },
          //       child: Row(
          //         mainAxisAlignment: MainAxisAlignment.center,
          //         crossAxisAlignment: CrossAxisAlignment.center,
          //         children: [
          //           Obx(() => Text(
          //                 vm._adName.value,
          //                 style: TextStyle(color: Colors.black),
          //               )),
          //           Container(
          //             margin: EdgeInsets.only(left: 24.w),
          //             child: Icon(
          //               Icons.expand_more,
          //               color: Color.fromRGBO(204, 204, 204, 1),
          //               size: 30.w,
          //             ),
          //           ),
          //         ],
          //       )),
          // ),
          // Container(
          //   width: 1.w,
          //   color: Color.fromRGBO(204, 204, 204, 1),
          // ),
          Expanded(
            child: TextButton(
                onPressed: () {
                  Pickers.showSinglePicker(
                    data: vm._waterTypeList,
                    selectData: vm._useWaterType.value.value,
                    onConfirm: vm._searchProjectType,
                  );
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      vm._useWaterType.value.name,
                      style: TextStyle(color: Colors.black),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 24.w),
                      child: Icon(
                        Icons.expand_more,
                        color: Color.fromRGBO(204, 204, 204, 1),
                        size: 30.w,
                      ),
                    ),
                  ],
                )),
          ),
        ],
      ),
    );
  }

  ///搜索栏
  Widget searchBar() {
    return Container(
      width: 1.sw,
      height: 150.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(37.w, 27.h, 37.w, 24.h),
            width: 989.w,
            height: 98.h,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(
                  Icons.search,
                  size: 48.w,
                  color: Color.fromRGBO(204, 204, 204, 1),
                ),
                SizedBox(
                  width: 33.w,
                ),
                Expanded(
                    child: TextField(
                  controller: vm._keywordsController,
                  style: TextStyle(height: 3.h, fontSize: 36.sp),
                  decoration: InputDecoration.collapsed(
                    hintText: '输入水表号或姓名',
                  ),
                  onChanged: (value) {
                    vm._searchKeyWords(value);
                  },
                ))
              ],
            ),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(48.w),
                border: Border.all(
                  color: Color.fromRGBO(204, 204, 204, 1),
                )),
          )
        ],
      ),
    );
  }

  ///用水户列表
  Widget waterUserList() {
    return Expanded(
        child: RefreshIndicator(
      onRefresh: vm._onRefresh,
      child: vm._userWaterList.length > 0
          ? ListView.builder(
              controller: vm._scrollController,
              itemCount: vm._userWaterList.length,
              physics: AlwaysScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return Column(children: [
                  waterUserItem(index),
                  SizedBox(
                    height: 20.h,
                  ),
                  _showMore(index)
                ]);
              },
            )
          : vm._flag
              ? NoDataWidget()
              : LoadingWidget(),
    ));
  }

  final SlidableController slidableController = SlidableController();

  ///工程项目
  ///
  ///[index]为该项目的索引
  Widget waterUserItem(index) {
    final isExpanded = false.obs;
    WaterUserItemModel item = vm._userWaterList[index];

    TextStyle subTitleStyle =
        TextStyle(color: Color.fromRGBO(96, 96, 96, 1), fontSize: 36.sp);
    return GestureDetector(
      onDoubleTap: () {
        Get.toNamed(
          '/water_user_detail',
          arguments: item,
        );
      },
      child: Container(
        // padding: EdgeInsets.fromLTRB(0, 37.h, 0, 0),
        color: Colors.white,
        child: Column(
          children: [
            Slidable(
                key: Key(item.id.toString()),
                controller: slidableController,
                actionPane: SlidableDrawerActionPane(),
                actionExtentRatio: 0.12,
                child: Column(
                  children: [
                    ///面版头部标题区域
                    Container(
                      width: 1.sw,
                      // color: Colors.red,
                      height: 143.h,
                      padding: EdgeInsets.fromLTRB(104.w, 0, 57.w, 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: Text(
                            '${item.username} - ${item.tableType == '1' ? item.baseNum : item.tableNum}',
                            style: TextStyle(
                                fontSize: 42.sp, fontWeight: FontWeight.w500),
                          )),
                          Text(
                            item.getStatusName(),
                            style: TextStyle(
                                color: item.getStatusColor(), fontSize: 36.sp),
                          )
                        ],
                      ),
                    ),

                    ///面板内容固定区域
                    Container(
                      width: 1.sw,
                      height: 170.h,
                      padding: EdgeInsets.fromLTRB(104.w, 0, 57.w, 35.h),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '基表号：${item.baseNum}',
                                style: subTitleStyle,
                              ),
                              Text(
                                '水表通经：${item.meterDiameter}mm',
                                style: subTitleStyle,
                              ),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text(
                                    '用水类型：',
                                    style: subTitleStyle,
                                  ),
                                  Text(
                                    '${item.priceName}',
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        color: Color.fromRGBO(96, 96, 96, 1),
                                        fontSize: item.priceName.length <= 6
                                            ? 36.sp
                                            : 34.sp),
                                  )
                                ],
                              ),
                              Text(
                                '归属地:${item.adName}',
                                overflow: TextOverflow.ellipsis,
                                style: subTitleStyle,
                              )
                            ],
                          )
                        ],
                      ),
                    ),

                    ///面板内容伸缩区域
                    Obx(() => AnimatedContainer(
                          padding: EdgeInsets.fromLTRB(104.w, 0, 57.w, 46.h),
                          width: 1.sw,
                          // color: Colors.orange,
                          duration: Duration(milliseconds: 200),
                          height: isExpanded.value ? 180.h : 0.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                children: [
                                  Expanded(
                                      child: Center(
                                    child: Text(
                                      '${item.realdata.value.getSwitchStatusName()}',
                                      style: TextStyle(
                                          color: item.realdata.value
                                              .getSwitchStatusColor(),
                                          fontSize: 48.sp,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  )),
                                  Expanded(
                                      child: Text(
                                    '开关状态',
                                    style: subTitleStyle,
                                  ))
                                ],
                              ),
                              Column(
                                children: [
                                  Expanded(
                                      child: Center(
                                    child: Text(
                                      '${item.realdata.value.totalFlow == null || item.realdata.value.totalFlow == '' ? '-' : item.realdata.value.totalFlow}',
                                      style: TextStyle(
                                          color: MyColors.main,
                                          fontSize: 48.sp,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  )),
                                  Expanded(
                                      child: Text(
                                    '累计流量(m³)',
                                    style: subTitleStyle,
                                  ))
                                ],
                              ),
                              Column(
                                children: [
                                  Expanded(
                                      child: Center(
                                    child: Text(
                                      '${item.realdata.value.voltage == null || item.realdata.value.voltage == '' ? '-' : item.realdata.value.voltage}',
                                      style: TextStyle(
                                          color: MyColors.main,
                                          fontSize: 48.sp,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  )),
                                  Expanded(
                                      child: Text(
                                    '电压(V)',
                                    style: subTitleStyle,
                                  ))
                                ],
                              ),
                              Column(
                                children: [
                                  Expanded(
                                      child: Center(
                                    child: Text(
                                      '${item.realdata.value.signal == null || item.realdata.value.signal == '' ? '-' : item.realdata.value.signal}',
                                      style: TextStyle(
                                          color: MyColors.main,
                                          fontSize: 48.sp,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  )),
                                  Expanded(
                                      child: Text(
                                    '信号强度',
                                    style: subTitleStyle,
                                  ))
                                ],
                              ),
                              Column(
                                children: [
                                  item.realdata.value.time != ''
                                      ? Expanded(
                                          child: Column(children: [
                                          Expanded(
                                            child: Text(
                                              '${item.realdata.value.time.split(' ')[0]}',
                                              textAlign: TextAlign.center,
                                              style: TextStyle(
                                                color: MyColors.main,
                                                fontSize: 30.sp,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                              child: Text(
                                            '${item.realdata.value.time.split(' ')[1]}',
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              color: MyColors.main,
                                              fontSize: 30.sp,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ))
                                        ]))
                                      : Expanded(
                                          child: Center(
                                            child: Text(
                                              '-',
                                              textAlign: TextAlign.center,
                                              style: TextStyle(
                                                color: MyColors.main,
                                                fontSize: 48.sp,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          ),
                                        ),
                                  Expanded(
                                      child: Text(
                                    '通讯时间',
                                    style: subTitleStyle,
                                  ))
                                ],
                              )
                            ],
                          ),
                        )),
                  ],
                ),

                ///侧滑区域
                secondaryActions: [
                  IconSlideAction(
                    color: Color.fromRGBO(11, 193, 80, 1),
                    iconWidget: Container(
                      child: Text(
                        '编辑',
                        style: TextStyle(color: Colors.white, fontSize: 36.sp),
                      ),
                    ),
                    onTap: () {
                      _showEditWaterUserDialog(vm._userWaterList[index]);
                    },
                  ),
                  IconSlideAction(
                    color: Color.fromRGBO(241, 15, 15, 1),
                    iconWidget: Container(
                      child: Text(
                        '删除',
                        style: TextStyle(color: Colors.white, fontSize: 36.sp),
                      ),
                    ),
                    onTap: () {
                      _showDelWaterUserDialog(index);
                    },
                  )
                ]),
            //底部收起展开栏
            Container(
              height: 100.h,
              // color: Colors.green,
              margin: EdgeInsets.only(left: 104.w, right: 56.w),
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1.w, color: Color.fromRGBO(0, 0, 0, 0.2)))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                      onPressed: () {
                        if (!isExpanded.value) {
                          vm.getUserRealData(index, item);
                        }
                        isExpanded.toggle();
                      },
                      child: Row(
                        children: [
                          Obx(() => Text(
                                isExpanded.value ? '收起' : '展开',
                                style: TextStyle(
                                  color: Color.fromRGBO(96, 96, 96, 0.6),
                                  fontSize: 36.sp,
                                ),
                              )),
                          Container(
                            margin: EdgeInsets.only(left: 20.w),
                            child: Obx(() => Icon(
                                  isExpanded.value
                                      ? Icons.expand_less
                                      : Icons.expand_more,
                                  size: 30.w,
                                  color: Color.fromRGBO(204, 204, 204, 1),
                                )),
                          )
                        ],
                      ))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///列表状态
  ///
  ///[index]为项目的索引
  Widget _showMore(index) {
    if (vm._hasMore.value) {
      if (index == vm._userWaterList.length - 1) {
        return LoadingWidget();
      } else {
        return Text('');
      }
    } else {
      return (index == vm._userWaterList.length - 1)
          ? Text('我是有底线的',
              style: TextStyle(
                color: Color.fromRGBO(119, 119, 119, 0.6),
                fontSize: 34.sp,
              ))
          : Text('');
    }
  }

  ///编辑弹窗
  _showEditWaterUserDialog(WaterUserItemModel value) {
    vm.userId = value.id;
    vm.username.value = value.username;
    vm.identityCard.value = value.identityCard;
    vm.address.value = value.address;
    vm.phone.value = value.phone;
    vm.familySize.value = value.familySize;
    vm.adId.value = value.adId;
    vm.adName.value = value.adName;
    vm.isBreeder.value = value.isBreeder;
    vm.breedNote.value = (value.breedNote != null ? value.breedNote : '')!;
    vm.note.value = (value.note != null ? value.note : '')!;
    vm.waterType.update((val) {
      val!.name = value.priceName;
      val.value = value.priceId.toString();
    });
    // vm._getWaterTypeList(value.adId, 0);
    showModalBottomSheet(
        context: vm.context,
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (context) {
          return Container(
              height: 0.8.sh,
              width: 1.sw,
              padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 50.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.w),
                      topRight: Radius.circular(30.w))),
              child: Column(children: [
                ModalTitle(
                    title: '用水户信息修改',
                    margin: 0,
                    onPressed: () {
                      Navigator.pop(context);
                    }),
                Expanded(
                    child: Form(
                        key: _formKey, //设置globalKey，用于后面获取FormState
                        child: Container(
                          // height: 0.5.sh,
                          width: 1.sw,
                          child: ListView(children: [
                            FormInput(
                              title: '姓名',
                              placeholder: '请输姓名',
                              initValue: vm.username.value,
                              request: true,
                              onChanged: (value) {
                                vm.username.value = value;
                              },
                            ),
                            FormInput(
                              title: '身份证号',
                              placeholder: '请输身份证号',
                              initValue: vm.identityCard.value,
                              request: true,
                              onChanged: (value) {
                                vm.identityCard.value = value;
                              },
                            ),
                            // FormAdPicker(
                            //     title: '归属地',
                            //     onConfirm: vm.adIdCof,
                            //     dataList: commonService.adList,
                            //     name: vm.adName,
                            //     value: vm.adId),
                            FormSinglePicker(
                                title: '用水类型',
                                onConfirm: vm.waterTypeCof,
                                dataList: vm.waterTypeList,
                                value: vm.waterType),
                            FormInput(
                              title: '手机号',
                              request: true,
                              initValue: vm.phone.value,
                              placeholder: '请输手机号码',
                              keyboardType: TextInputType.phone,
                              onChanged: (value) {
                                vm.phone.value = value;
                              },
                            ),
                            FormNumber(
                              title: '用水人口',
                              request: true,
                              controller: TextEditingController(
                                  text: vm.familySize.value.toString()),
                              placeholder: '请输用水人口',
                              onChanged: (value) {
                                vm.familySize.value =
                                    NumUtil.getNumByValueDouble(
                                        NumUtil.getDoubleByValueStr(value),
                                        0) as int;
                              },
                            ),
                            FormInput(
                              title: '住址',
                              placeholder: '请输住址',
                              initValue: vm.address.value,
                              request: true,
                              onChanged: (value) {
                                vm.address.value = value;
                              },
                            ),
                            FormRadio(
                              title: '是否养殖',
                              dataList: vm.breederList,
                              groupValue: vm.isBreeder,
                            ),
                            Obx(() => vm.isBreeder.value == '1'
                                ? FormTextArea(
                                    placeholder: '填写养殖信息',
                                    request: true,
                                    controller: TextEditingController(
                                        text: vm.breedNote.value),
                                    onChanged: (value) {
                                      vm.breedNote.value = value;
                                    },
                                  )
                                : Container()),
                            FormTextArea(
                              title: '备注',
                              placeholder: '填写备注信息',
                              hasBorder: false,
                              controller:
                                  TextEditingController(text: vm.note.value),
                              onChanged: (value) {
                                vm.note.value = value;
                              },
                            ),
                            _saveButton()
                          ]),
                        )))
              ]));
        });
  }

  ///删除弹窗
  _showDelWaterUserDialog(index) {
    MyDialog.confirmDialog(
        title: '删除',
        desc: '是否确定删除此项？',
        onConfirm: () {
          SmartDialog.dismiss();
          vm._deleteWaterUser(index, vm._userWaterList[index]);
        });
  }

  ///保存按钮
  Widget _saveButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          child: ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate() && vm._validateForm()) {
                vm._saveForm();
              } else {
                print(vm._validateForm());
              }
            },
            child: Text('保  存'),
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.white),
                backgroundColor: MaterialStateProperty.all(MyColors.main),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(72.w)))),
                textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                ))),
          ),
        )
      ],
    );
  }
}

///用水户列表页控制器
class WaterUserListPageController extends GetxController {
  CommonService commonService = Get.find();
  late BuildContext context;

  ///下滑判断开关
  bool _flag = true;

  ///页码
  int _page = 1;

  ///一页多少个
  int _pageSize = 10;

  ///是否有更多
  final _hasMore = true.obs;

  ///是否有数据
  final _hasData = true.obs;

  ///行政区划名称
  final _adName = '行政区划'.obs;

  ///行政区划id
  int? _adId = 0;

  ///模糊查询
  String _keywords = '';

  ///工程id(路由传参传入)
  int? _pj_id = 0;

  ///工程名称(路由传参传入)

  String? _pj_name;

  ///工程类型表单id
  final _projectTypeId = PickerItemModel().obs;

  var username = ''.obs; //户名
  var identityCard = ''.obs; //身份证号
  var address = ''.obs; //详细地址
  final waterType = PickerItemModel().obs; //用水类型
  List<PickerItemModel> waterTypeList = []; //获用水类型列表
  var phone = ''.obs; //手机号
  final familySize = 1.obs; //用水人口
  var adId = Rx<int>(0); //归属地-id
  var adName = ''.obs; //归属地-名称
  var isBreeder = '0'.obs; //是否养殖
  var breedNote = ''.obs; //养殖说明
  var note = ''.obs; //备注
  ///用水id
  int userId = 0;
  List breederList = [
    {'name': "否", 'value': '0'},
    {'name': "是", 'value': '1'},
  ]; //是否养殖

  ///模糊查询的控制器
  TextEditingController _keywordsController = TextEditingController();

  ///用水类型id
  final _useWaterType =
      PickerItemModel(name: '用水类型', value: '0', creditLevel: '').obs;

  ///用水类型列表
  List<PickerItemModel> _waterTypeList = [
    PickerItemModel(name: '全部', value: '0')
  ];

  ///ListView滑动控制器
  ScrollController _scrollController = ScrollController();
  final _userWaterList = <WaterUserItemModel>[].obs;

  /*用水类型选择 */
  waterTypeCof(PickerItemModel value) {
    waterType(value);
  }

  /* 归属地选择 */
  adIdCof(List<AdItemModel> data) {
    adName.value = data.map((e) => e.name).toList().join('-');
    adId.value = data[data.length - 1].id;
    // _getWaterTypeList(adId.value, 0);
  }

  @override
  void onInit() async {
    _page = 1;
    if (Get.arguments != null) {
      _keywords = Get.arguments.params;
      _keywordsController.text = Get.arguments.params;

      _pj_id = Get.arguments.id;
      _pj_name = Get.arguments.name;
      _adId = Get.arguments.ad_id;
    }
    final availableMaps = await MapLauncher.installedMaps;
    availableMaps.forEach((element) {
      print(element.mapName);
    });
    print(availableMaps);
    _getWaterTypeList(adId.value);

    ///初始化时先拿一次数据
    getWaterUserListData();

    ///监听ListView滚动事件

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (_flag && _hasMore.value) {
          getWaterUserListData();
        }
      } else {}
    });
    super.onInit();
  }

  ///获取用水类型
  _getWaterTypeList(int id) async {
    try {
      var res = await Http().post(ApiWater.WATER_PRICE_LIST, data: {
        "paginate": {"total": 0, "page": 1, "per_page": 20},
        "params": {"ad_id": id, "params": ""}
      });
      WaterTypeResultModel result = WaterTypeResultModel.fromJson(res);

      if (result.code == 200) {
        result.content.data.forEach((element) {
          _waterTypeList.add(PickerItemModel(
              name: element.name,
              value: element.id.toString(),
              creditLevel: element.creditLevel));
          waterTypeList.add(PickerItemModel(
              name: element.name,
              value: element.id.toString(),
              creditLevel: element.creditLevel));
        });
      } else {}
    } catch (e) {
      print(e);
    }
  }

  ///获取用水户列表
  Future<void> getWaterUserListData() async {
    _flag = false;

    try {
      if (_keywords == null) _keywords = '';
      var res = await Http().post(
        ApiWater.WATER_USER_LIST,
        data: {
          'params': {
            "project_id": _pj_id,
            "ad_id": _adId,
            "params": _keywords,
            "type_id": int.parse(_useWaterType.value.value)
          },
          'paginate': {"total": 0, "page": _page, 'per_page': _pageSize},
        },
      );
      WaterUserListResultModel result = WaterUserListResultModel.fromJson(res);
      if (result.code == 200) {
        _userWaterList.addAll(result.content.data);
        _page++;
        _flag = true;
        if (result.content.data.length < _pageSize) {
          _hasMore.value = false;
        }
        if (_userWaterList.length == 0) {
          _hasData.value = false;
        } else {
          _hasData.value = true;
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  ///下拉刷新
  Future<void> _onRefresh() async {
    resetParams();

    //重新请求数据
    await getWaterUserListData();
  }

  ///重置查询数据
  resetParams() {
    //重置分页数
    _page = 1;

    //重置数据
    _userWaterList.clear();

    //滚动条回到顶部
    if (_userWaterList.length > 0) {
      _scrollController.jumpTo(0);
    }

    //重置hasmore
    _hasMore.value = true;
  }

  ///模糊搜索事件
  Future<void> _searchKeyWords(value) async {
    _keywords = value;
    resetParams();

    //重新请求数据
    await getWaterUserListData();
  }

  ///按工程类型查询
  _searchProjectType(PickerItemModel value) async {
    print(value);
    _useWaterType(value);
    resetParams();

    ///重新请求数据
    await getWaterUserListData();
  }

  ///按行政区划查询
  _searchAdId(dynamic data) async {
    resetParams();

    if (data == null) {
      _adName.value = '全部';
      _adId = 0;
    } else {
      _adName.value = data[data.length - 1].name;
      _adId = data[data.length - 1].id;
    }
    // await _getWaterTypeList(_adId!, 1);

    ///重新请求数据
    await getWaterUserListData();
  }

  ///基础验证
  _validateForm() {
    var msg = '';
    if (adId.value == null || adId.value == 0) {
      msg = '请选择行政区划';
    } else if (waterType.value.value == null) {
      msg = '请选择用水类型';
    }
    if (msg != '') {
      SmartDialog.showToast(msg, alignment: Alignment.center);
      return false;
    } else {
      return true;
    }
  }

  ///修改用水户
  _saveForm() async {
    MyDialog.showLoading(msg: '保存用水户信息');
    try {
      var res = await Http().put(ApiWater.WATER_USER_EDIT, data: {
        "id": userId,
        "family_size": familySize.value,
        "phone": phone.value,
        "note": note.value,
        "address": address.value,
        "is_breeder": isBreeder.value,
        "breed_note": breedNote.value,
        "ad_id": adId.value,
        "price_id": int.parse(waterType.value.value),
        'credit_level': waterType.value.creditLevel,
        "username": username.value,
        "identity_card": identityCard.value,
      });
      ResultModel result = ResultModel.fromJson(res);
      SmartDialog.dismiss();
      if (result.code == 200) {
        Get.back();
        SmartDialog.showToast('修改成功!', alignment: Alignment.center);
        resetParams();

        ///重新请求数据
        await getWaterUserListData();
      } else {
        SmartDialog.showToast('修改失败!', alignment: Alignment.center);
      }
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  ///获取用户实时数据
  getUserRealData(int index, WaterUserItemModel item) async {
    try {
      var res = await Http().post(ApiWater.DEVICE_DATA_REAL,
          data: {'address': item.tableNum, 'ad_code': item.adCode});

      UserRealDataResultModel result = UserRealDataResultModel.fromJson(res);
      if (result.code == 200) {
        item.realdata(result.content.data);
      }
    } catch (e) {}
  }

  ///删除用水户
  _deleteWaterUser(index, item) async {
    List<int> ids = [item.id];
    MyDialog.showLoading(msg: '删除中...');
    var res = await Http().delete(ApiWater.WATER_USER_DEL, data: {'ids': ids});
    SmartDialog.dismiss();
    ResultModel result = ResultModel.fromJson(res);
    if (result.code == 200) {
      _userWaterList.removeAt(index);
      SmartDialog.showToast('删除成功');
    } else {
      SmartDialog.showToast('删除失败');
    }
  }
}
